<template>
  <div class="schedule-statistics">
    <div class="page-header">
      <h2>排课统计</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="学期">
          <el-select v-model="filterForm.semester" placeholder="请选择学期" style="width: 160px" @change="handleSemesterChange">
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>刷新数据
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <div class="stats-overview">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon classroom">
            <el-icon size="40"><House /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ overviewStats.classroomUtilization }}%</div>
            <div class="stat-label">教室利用率</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon teacher">
            <el-icon size="40"><Avatar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ overviewStats.teacherWorkload }}</div>
            <div class="stat-label">平均教师工作量</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon course">
            <el-icon size="40"><Reading /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ overviewStats.totalCourses }}</div>
            <div class="stat-label">总课程数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon conflict">
            <el-icon size="40"><Warning /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ overviewStats.conflictCount }}</div>
            <div class="stat-label">冲突数量</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 教室利用率图表 -->
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>教室利用率统计</span>
          </div>
        </template>
        <div class="chart-container">
          <div class="chart-placeholder">
            <el-icon size="60" color="#409EFF"><TrendCharts /></el-icon>
            <p>教室利用率图表</p>
            <div class="chart-data">
              <div v-for="(item, index) in classroomStats" :key="index" class="data-item">
                <span class="data-label">{{ item.name }}</span>
                <el-progress :percentage="item.utilization" :color="getProgressColor(item.utilization)" />
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 教师工作量分布 -->
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>教师工作量分布</span>
          </div>
        </template>
        <div class="chart-container">
          <div class="chart-placeholder">
            <el-icon size="60" color="#67C23A"><PieChart /></el-icon>
            <p>教师工作量分布图</p>
            <div class="workload-list">
              <div v-for="(item, index) in teacherWorkloadStats" :key="index" class="workload-item">
                <div class="teacher-info">
                  <span class="teacher-name">{{ item.teacherName }}</span>
                  <span class="workload-hours">{{ item.totalHours }}课时</span>
                </div>
                <el-progress :percentage="item.workloadPercentage" :color="getWorkloadColor(item.workloadPercentage)" />
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 课程分布统计 -->
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>课程分布统计</span>
          </div>
        </template>
        <div class="chart-container">
          <div class="chart-placeholder">
            <el-icon size="60" color="#E6A23C"><DataAnalysis /></el-icon>
            <p>课程分布统计图</p>
            <div class="course-distribution">
              <div v-for="(item, index) in courseDistributionStats" :key="index" class="distribution-item">
                <div class="distribution-info">
                  <span class="course-type">{{ item.type }}</span>
                  <span class="course-count">{{ item.count }}门</span>
                </div>
                <div class="distribution-bar">
                  <div class="bar-fill" :style="{ width: item.percentage + '%', backgroundColor: getDistributionColor(index) }"></div>
                </div>
                <span class="percentage">{{ item.percentage }}%</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 排课质量分析 -->
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>排课质量分析</span>
          </div>
        </template>
        <div class="chart-container">
          <div class="chart-placeholder">
            <el-icon size="60" color="#F56C6C"><Monitor /></el-icon>
            <p>排课质量分析图</p>
            <div class="quality-metrics">
              <div class="metric-item">
                <span class="metric-label">时间冲突率</span>
                <el-progress :percentage="qualityStats.timeConflictRate" :color="getQualityColor(qualityStats.timeConflictRate)" />
              </div>
              <div class="metric-item">
                <span class="metric-label">教室利用率</span>
                <el-progress :percentage="qualityStats.classroomUtilization" :color="getQualityColor(qualityStats.classroomUtilization)" />
              </div>
              <div class="metric-item">
                <span class="metric-label">教师满意度</span>
                <el-progress :percentage="qualityStats.teacherSatisfaction" :color="getQualityColor(qualityStats.teacherSatisfaction)" />
              </div>
              <div class="metric-item">
                <span class="metric-label">学生满意度</span>
                <el-progress :percentage="qualityStats.studentSatisfaction" :color="getQualityColor(qualityStats.studentSatisfaction)" />
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, House, Avatar, Reading, Warning, TrendCharts, PieChart, DataAnalysis, Monitor } from '@element-plus/icons-vue'
import { 
  getClassroomUtilizationStats,
  getTeacherWorkloadStats,
  getCourseDistributionStats,
  getScheduleQualityAnalysis,
  getConflictStats
} from '../api/scheduleStatistics'

const filterForm = reactive({
  semester: '2024春季'
})

// 概览统计数据
const overviewStats = ref({
  classroomUtilization: 0,
  teacherWorkload: 0,
  totalCourses: 0,
  conflictCount: 0
})

// 教室利用率统计
const classroomStats = ref([])

// 教师工作量统计
const teacherWorkloadStats = ref([])

// 课程分布统计
const courseDistributionStats = ref([])

// 排课质量分析
const qualityStats = ref({
  timeConflictRate: 0,
  classroomUtilization: 0,
  teacherSatisfaction: 0,
  studentSatisfaction: 0
})

// 工具函数
const getProgressColor = (percentage) => {
  if (percentage >= 80) return '#67C23A'
  if (percentage >= 60) return '#E6A23C'
  return '#F56C6C'
}

const getWorkloadColor = (percentage) => {
  if (percentage >= 80) return '#F56C6C'
  if (percentage >= 60) return '#E6A23C'
  return '#67C23A'
}

const getDistributionColor = (index) => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  return colors[index % colors.length]
}

const getQualityColor = (percentage) => {
  if (percentage >= 80) return '#67C23A'
  if (percentage >= 60) return '#E6A23C'
  return '#F56C6C'
}

// 事件处理
const handleSemesterChange = () => {
  fetchAllStats()
}

const handleRefresh = () => {
  fetchAllStats()
}

// 数据获取
const fetchAllStats = async () => {
  try {
    await Promise.all([
      fetchClassroomStats(),
      fetchTeacherStats(),
      fetchCourseStats(),
      fetchQualityStats(),
      fetchConflictStats()
    ])
  } catch (error) {
    console.warn('获取统计数据失败，使用模拟数据:', error)
    loadMockData()
  }
}

// 通用：按当前学期->其他学期 回退获取
const fetchWithFallback = async (apiFunc, judgeFn) => {
  const candidates = [filterForm.semester, '2025春季', '2024秋季']
  const tried = new Set()
  for (const sem of candidates) {
    if (!sem || tried.has(sem)) continue
    tried.add(sem)
    try {
      const res = await apiFunc(sem)
      if (res && res.data && (!judgeFn || judgeFn(res.data))) {
        return { data: res.data, semester: sem }
      }
    } catch (e) {
      // 忽略，尝试下一个
    }
  }
  return { data: null, semester: candidates[0] }
}

const fetchClassroomStats = async () => {
  try {
    const { data: d, semester: used } = await fetchWithFallback(getClassroomUtilizationStats, d => (d.classroomList && d.classroomList.length) || d.averageUtilization)
    if (d) {
      classroomStats.value = d.classroomList || d.list || []
      overviewStats.value.classroomUtilization = d.averageUtilization ?? d.avgUtilization ?? 0
      if (used !== filterForm.semester) {
        filterForm.semester = used
      }
      if ((!classroomStats.value || classroomStats.value.length === 0) && !overviewStats.value.classroomUtilization) {
        ElMessage.info('该学期暂无教室利用率数据')
      }
    }
  } catch (error) {
    console.warn('获取教室统计失败:', error)
  }
}

const fetchTeacherStats = async () => {
  try {
    const { data: d, semester: used } = await fetchWithFallback(getTeacherWorkloadStats, d => (d.teacherList && d.teacherList.length) || d.averageWorkload)
    if (d) {
      teacherWorkloadStats.value = d.teacherList || d.list || []
      overviewStats.value.teacherWorkload = d.averageWorkload ?? d.avgWorkload ?? 0
      if (used !== filterForm.semester) {
        filterForm.semester = used
      }
      if ((!teacherWorkloadStats.value || teacherWorkloadStats.value.length === 0) && !overviewStats.value.teacherWorkload) {
        ElMessage.info('该学期暂无教师工作量数据')
      }
    }
  } catch (error) {
    console.warn('获取教师统计失败:', error)
  }
}

const fetchCourseStats = async () => {
  try {
    const { data: d, semester: used } = await fetchWithFallback(getCourseDistributionStats, d => (d.distribution && d.distribution.length) || d.totalCourses)
    if (d) {
      courseDistributionStats.value = d.distribution || []
      overviewStats.value.totalCourses = d.totalCourses ?? 0
      if (used !== filterForm.semester) {
        filterForm.semester = used
      }
      if ((!courseDistributionStats.value || courseDistributionStats.value.length === 0) && !overviewStats.value.totalCourses) {
        ElMessage.info('该学期暂无课程分布数据')
      }
    }
  } catch (error) {
    console.warn('获取课程统计失败:', error)
  }
}

const fetchQualityStats = async () => {
  try {
    const { data: d, semester: used } = await fetchWithFallback(getScheduleQualityAnalysis)
    if (d) {
      qualityStats.value = {
        timeConflictRate: d.timeConflictRate ?? 0,
        classroomUtilization: d.classroomUtilization ?? 0,
        teacherSatisfaction: d.teacherSatisfaction ?? 0,
        studentSatisfaction: d.studentSatisfaction ?? 0
      }
      if (used && used !== filterForm.semester) {
        filterForm.semester = used
      }
    }
  } catch (error) {
    console.warn('获取质量分析失败:', error)
  }
}

const fetchConflictStats = async () => {
  try {
    const { data: d, semester: used } = await fetchWithFallback(getConflictStats)
    if (d) {
      overviewStats.value.conflictCount = d.totalConflicts || 0
      if (used && used !== filterForm.semester) {
        filterForm.semester = used
      }
    }
  } catch (error) {
    console.warn('获取冲突统计失败:', error)
  }
}

// 加载模拟数据
const loadMockData = () => {
  // 概览统计
  overviewStats.value = {
    classroomUtilization: 75,
    teacherWorkload: 18,
    totalCourses: 156,
    conflictCount: 3
  }

  // 教室统计
  classroomStats.value = [
    { name: 'A101', utilization: 85 },
    { name: 'A102', utilization: 72 },
    { name: 'B201', utilization: 68 },
    { name: 'B202', utilization: 90 },
    { name: 'C301', utilization: 55 }
  ]

  // 教师工作量
  teacherWorkloadStats.value = [
    { teacherName: '张老师', totalHours: 20, workloadPercentage: 80 },
    { teacherName: '李老师', totalHours: 16, workloadPercentage: 64 },
    { teacherName: '王老师', totalHours: 24, workloadPercentage: 96 },
    { teacherName: '赵老师', totalHours: 12, workloadPercentage: 48 }
  ]

  // 课程分布
  courseDistributionStats.value = [
    { type: '必修课', count: 45, percentage: 65 },
    { type: '选修课', count: 20, percentage: 29 },
    { type: '实践课', count: 4, percentage: 6 }
  ]

  // 质量分析
  qualityStats.value = {
    timeConflictRate: 5,
    classroomUtilization: 75,
    teacherSatisfaction: 85,
    studentSatisfaction: 78
  }
}

onMounted(() => {
  fetchAllStats()
})
</script>

<style scoped>
.schedule-statistics {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 16px;
  margin-right: 24px;
}

.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stat-icon.classroom {
  background: linear-gradient(135deg, #409EFF, #67C23A);
  color: white;
}

.stat-icon.teacher {
  background: linear-gradient(135deg, #67C23A, #E6A23C);
  color: white;
}

.stat-icon.course {
  background: linear-gradient(135deg, #E6A23C, #F56C6C);
  color: white;
}

.stat-icon.conflict {
  background: linear-gradient(135deg, #F56C6C, #909399);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background: #ffffff;
}

.chart-card :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
  color: #495057;
}

.chart-container {
  padding: 20px;
  min-height: 300px;
}

.chart-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: #6c757d;
}

.chart-placeholder p {
  margin: 12px 0;
  font-size: 16px;
  font-weight: 500;
}

.chart-data {
  width: 100%;
  margin-top: 20px;
}

.data-item {
  margin-bottom: 16px;
}

.data-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #495057;
}

.workload-list {
  width: 100%;
  margin-top: 20px;
}

.workload-item {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.teacher-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.teacher-name {
  font-weight: 500;
  color: #495057;
}

.workload-hours {
  font-size: 12px;
  color: #6c757d;
}

.course-distribution {
  width: 100%;
  margin-top: 20px;
}

.distribution-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.distribution-info {
  display: flex;
  justify-content: space-between;
  width: 120px;
  margin-right: 16px;
}

.course-type {
  font-weight: 500;
  color: #495057;
}

.course-count {
  font-size: 12px;
  color: #6c757d;
}

.distribution-bar {
  flex: 1;
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  margin-right: 12px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.percentage {
  font-size: 12px;
  color: #6c757d;
  min-width: 40px;
  text-align: right;
}

.quality-metrics {
  width: 100%;
  margin-top: 20px;
}

.metric-item {
  margin-bottom: 20px;
}

.metric-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #495057;
  font-weight: 500;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>











